'''

    The kababatch command line is used to execute
    an App command.

'''


import sys
import os
import kabaret.core.cmdln as cmdln


class KabaBatch(cmdln.Cmdln):
    '''Usage:
        {name} SUBCOMMAND [ARGS...]
        {name} help SUBCOMMAND
        
    ${command_list}
    ${help_list}
    
    '''%({'name':'kababatch'})
    
    def __init__(self, *args, **kwargs):
        cmdln.Cmdln.__init__(self, *args, **kwargs)
        cmdln.Cmdln.do_help.aliases.append('h') #@UndefinedVariable from decorator


    @cmdln.option(
        '-v', '--verbose', action='store_true',
        help='print extra information'
    )
#    @cmdln.option(
#        '-n', '--dry-run', action='store_true',
#        help='Print the command that would be executed, but do not execute.'
#    )
#    @cmdln.option(
#        '-u', '--url_host',  metavar='ARG',
#        help='The host name or IP of the Url service used to connect to an AppHost. (Not implemented yet!)'
#    )
    @cmdln.option(
        '-P', '--project', metavar='ARG',
        help='The name of the project to connect to.'
    )
    @cmdln.option(
        '-A', '--app', metavar='ARG',
        help='The name of the app to use.'
    )
    @cmdln.option(
        '-C', '--cmd', metavar='ARG',
        help='The name of the command to call.'
    )
    def do_run(self, subcmd, opts, *args):
        '''Run an app command in a project
        usage:
            run [command arguments]
                    
        ${cmd_option_list}
        '''
#        if opts.url_host is not None:
#            raise cmdln.CmdlnUserError('The --url_host option (-u) is not supported yet.')

        if opts.project is None:
            raise cmdln.CmdlnUserError('Missing -P or --project')
        if opts.app is None:
            raise cmdln.CmdlnUserError('Missing -A or --app')
        if opts.cmd is None:
            raise cmdln.CmdlnUserError('Missing -C or --cmd')

        verbose = opts.verbose
        
        import kabaret.core.apphost
        import kabaret.core.ro.url
        
        try:
            if verbose:
                print
            
            if verbose:
                print 'Contacting Project', opts.project
            project_url = kabaret.core.ro.url.For.project(opts.project)
            project = kabaret.core.ro.url.resolve(project_url, local=False)

            if verbose:
                print 'Launching AppHost on project', opts.project
            app_host = kabaret.core.apphost.AppHost(project)
            if verbose:
                print '\nAppHost ready for kababatch\n\n'
                 
            if verbose:
                print 'Getting app', opts.app
            app = app_host.app(opts.app)
            
            if verbose:
                print 'Getting app command', opts.cmd
            cmd = getattr(app.cmds, opts.cmd)
            
            if verbose:
                print 'Calling cmd with args:', args, '\n\n'
            ret = cmd(*args)
            
            if verbose:
                print 'Result:', repr(ret)
                
        except Exception, err:
            msg = 'There was an error while executing batch command(s): %s'%(err,)
            if opts.verbose:
                import traceback
                msg += '\n'+traceback.format_exc()
            else:
                msg += '\nUse -v or --verbose to see the traceback\n'
            raise cmdln.CmdlnUserError(msg)

if __name__ == "__main__":
    kababatch = KabaBatch()
    kababatch.main()
